<template>
  <div class="spread">
    <div
      :class="{ 'ellipsis-auto': !expanded }"
      :style="[{ '-webkit-line-clamp': maxLine }]"
      ref="text"
    >
      <slot></slot>
    </div>
    <div class="text-right" v-show="showMore">
      <q-btn
        dense
        flat
        :color="btnColor"
        :label="label"
        @click="toggle"
      ></q-btn>
    </div>
  </div>
</template>
<script>
import { dom } from "quasar";

export default {
  name: "ellipsisText",
  data() {
    return {
      expanded: true,
      showMore: false,
    };
  },
  props: {
    maxLine: {
      type: Number,
      default: 0,
    },
    expandText: {
      type: String,
      default: "展开",
    },
    shrinkText: {
      type: String,
      default: "收起",
    },
    btnColor: {
      type: String,
      default: "primary",
    },
  },
  computed: {
    label() {
      return this.expanded ? this.shrinkText : this.expandText;
    },
  },
  methods: {
    toggle() {
      this.expanded = !this.expanded;
    },
  },
  mounted() {
    const lineHeight = parseInt(dom.style(this.$refs.text, "line-height"));
    const height = dom.height(this.$refs.text);
    if (height / lineHeight > this.maxLine) {
      this.expanded = false;
      this.showMore = true;
    }
  },
};
</script>

<style scoped>
.ellipsis-auto {
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
